import React, { useEffect } from 'react';
import { Card, Typography, Space, Button, Image, Tag, Tooltip, Modal } from 'antd';
import {
  FileImageOutlined,
  VideoCameraOutlined,
  FilePdfOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FilePptOutlined,
  FileTextOutlined,
  DownloadOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons';

const { Text } = Typography;

const AttachmentPreview = ({ attachments = [], onDelete, showActions = false, preferPdfPreview = false }) => {
  // 添加全屏模态框样式
  useEffect(() => {
    const style = document.createElement('style');
    style.textContent = `
      .fullscreen-modal .ant-modal {
        max-width: none !important;
        margin: 0 !important;
        padding: 0 !important;
      }
      .fullscreen-modal .ant-modal-content {
        border-radius: 0 !important;
      }
      .document-preview-modal .ant-modal-header {
        border-bottom: 1px solid #f0f0f0;
        padding: 12px 24px;
      }
      .document-preview-modal .ant-modal-body {
        padding: 0;
      }
      .document-preview-modal .ant-modal-footer {
        border-top: 1px solid #f0f0f0;
        padding: 10px 16px;
      }
    `;
    document.head.appendChild(style);
    
    return () => {
      document.head.removeChild(style);
    };
  }, []);
  // 获取文件图标
  const getFileIcon = (fileType, mimeType) => {
    if (fileType === 'image') return <FileImageOutlined />;
    if (fileType === 'video') return <VideoCameraOutlined />;
    
    if (mimeType) {
      if (mimeType.includes('pdf')) return <FilePdfOutlined />;
      if (mimeType.includes('word') || mimeType.includes('document')) return <FileWordOutlined />;
      if (mimeType.includes('sheet') || mimeType.includes('excel')) return <FileExcelOutlined />;
      if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) return <FilePptOutlined />;
    }
    
    return <FileTextOutlined />;
  };

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 获取文件类型标签颜色
  const getFileTypeColor = (fileType) => {
    switch (fileType) {
      case 'image': return 'green';
      case 'video': return 'blue';
      case 'document': return 'orange';
      default: return 'default';
    }
  };

  // 获取完整的文件URL
  const getFullUrl = (url) => {
    if (url.startsWith('http')) {
      return url;
    }
    return `http://211.86.197.10:9091${url}`;
  };

  // 处理文件下载
  const handleDownload = (attachment) => {
    const link = document.createElement('a');
    link.href = getFullUrl(attachment.file_url);
    link.download = attachment.original_name;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 处理文件预览
  const handlePreview = async (attachment) => {
    if (attachment.file_type === 'image') {
      // 图片预览已经通过 Image 组件处理
      return;
    }
    
    const fileUrl = getFullUrl(attachment.file_url);
    const fileName = attachment.original_name;
    const fileType = attachment.mime_type;
    
    console.log('预览附件:', { fileName, fileType, attachmentId: attachment.id, preferPdfPreview });
    
    // 检查是否是Word或PPT文档，如果启用PDF优先预览且有PDF版本，直接预览PDF
    const isWordOrPpt = [
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'application/vnd.ms-powerpoint'
    ].includes(fileType);

    // 如果是PDF文档，直接预览
    if (fileType === 'application/pdf') {
      console.log('检测到PDF文档，直接预览');
      showOfficeDocumentModal(fileName, 'application/pdf', fileUrl, attachment);
      return;
    }

    // 如果启用PDF优先预览且是Word/PPT文档，尝试获取PDF版本
    if (preferPdfPreview && isWordOrPpt && attachment.id) {
      try {
        console.log('尝试获取PDF版本:', attachment.id);
        const pdfResponse = await fetch(`http://211.86.197.10:9091/api/attachments/${attachment.id}/pdf`);
        
        if (pdfResponse.ok) {
          const pdfResult = await pdfResponse.json();
          if (pdfResult.success && pdfResult.data && pdfResult.data.pdf_url) {
            console.log('找到PDF版本，直接预览PDF');
            const pdfUrl = getFullUrl(pdfResult.data.pdf_url);
            showOfficeDocumentModal(fileName, 'application/pdf', pdfUrl, attachment);
            return;
          }
        }
      } catch (error) {
        console.log('获取PDF版本失败，继续原有流程:', error);
      }
    }
    
    // 检查是否是Office文档或其他可转换的文档
    const isConvertibleDocument = [
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'application/vnd.ms-powerpoint',
      'text/plain'
    ].includes(fileType);

    if (isConvertibleDocument && attachment.id) {
      // 显示加载状态
      const loadingModal = Modal.info({
        title: (
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span>🔄</span>
            <span>正在处理文档...</span>
          </div>
        ),
        content: (
          <div style={{ textAlign: 'center', padding: '20px' }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>📄</div>
            <p><strong>{fileName}</strong></p>
            <p style={{ color: '#666' }}>
              {isWordOrPpt ? '正在转换为PDF格式，请稍候...' : '正在将文档转换为HTML格式，请稍候...'}
            </p>
            <div style={{ 
              width: '100%', 
              height: '4px', 
              background: '#f0f0f0', 
              borderRadius: '2px',
              overflow: 'hidden',
              marginTop: '16px'
            }}>
              <div style={{
                width: '30%',
                height: '100%',
                background: 'linear-gradient(90deg, #1890ff, #722ed1)',
                borderRadius: '2px',
                animation: 'loading 2s ease-in-out infinite'
              }}></div>
            </div>
            <style>{`
              @keyframes loading {
                0% { transform: translateX(-100%); }
                50% { transform: translateX(200%); }
                100% { transform: translateX(300%); }
              }
            `}</style>
          </div>
        ),
        okText: '取消',
        onOk: () => loadingModal.destroy()
      });

      try {
        console.log('尝试转换文档:', attachment.id);
        
        // 对于Word/PPT文档，优先尝试PDF转换
        if (isWordOrPpt) {
          try {
            const pdfResponse = await fetch(`http://211.86.197.10:9091/api/documents/${attachment.id}/convert-pdf`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              }
            });

            if (pdfResponse.ok) {
              const pdfResult = await pdfResponse.json();
              if (pdfResult.success && pdfResult.data && pdfResult.data.pdfUrl) {
                loadingModal.destroy();
                console.log('PDF转换成功，直接预览PDF');
                const pdfUrl = getFullUrl(pdfResult.data.pdfUrl);
                showOfficeDocumentModal(fileName, 'application/pdf', pdfUrl, attachment);
                return;
              }
            }
          } catch (pdfError) {
            console.log('PDF转换失败，尝试HTML转换:', pdfError);
          }
        }
        
        // 尝试HTML转换
        const response = await fetch(`http://211.86.197.10:9091/api/documents/${attachment.id}/convert`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        // 关闭加载模态框
        loadingModal.destroy();

        console.log('转换API响应状态:', response.status);
        
        if (!response.ok) {
          const errorText = await response.text();
          console.error('转换API错误:', response.status, errorText);
          throw new Error(`转换失败: ${response.status}`);
        }

        const result = await response.json();
        console.log('转换结果:', result.success ? '成功' : '失败', result.message);

        if (result.success && result.data && result.data.html) {
          // 显示转换后的HTML内容
          showConvertedDocument(fileName, result.data, attachment, fileUrl);
          return;
        } else {
          console.log('转换失败，显示默认界面');
          throw new Error(result.message || '转换失败');
        }
      } catch (error) {
        // 关闭加载模态框
        loadingModal.destroy();
        console.error('文档转换失败:', error);
        
        // 显示转换失败提示
        Modal.error({
          title: '文档转换失败',
          content: (
            <div>
              <p>无法将此文档转换为预览格式。</p>
              <p style={{ color: '#666', fontSize: '14px' }}>
                错误信息: {error.message}
              </p>
              <p>您可以选择下载原文件或在新窗口中打开。</p>
            </div>
          ),
          okText: '了解',
          onOk: () => {
            // 显示默认的Office文档界面
            showOfficeDocumentModal(fileName, fileType, fileUrl, attachment);
          }
        });
        return;
      }
    }
    
    // 显示默认的Office文档预览界面
    showOfficeDocumentModal(fileName, fileType, fileUrl, attachment);
  };

  // 显示转换后的文档
  const showConvertedDocument = (fileName, data, attachment, fileUrl) => {
    const modal = Modal.info({
      title: (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'space-between',
          gap: '8px',
          paddingRight: '40px'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span>📄</span>
            <span style={{ fontWeight: 600 }}>{fileName}</span>
            <Tag color="green" size="small">HTML预览</Tag>
          </div>
          <Space size="small">
            <Tooltip title="全屏预览">
              <Button 
                size="small"
                type="text"
                icon={<span style={{ fontSize: '16px' }}>⛶</span>}
                onClick={() => {
                  modal.destroy();
                  showFullscreenModal(fileName, data.html, data.warnings, attachment, fileUrl);
                }}
              />
            </Tooltip>
          </Space>
        </div>
      ),
      width: '90%',
      style: { top: 20 },
      className: 'document-preview-modal',
      maskClosable: true,
      content: (
        <div style={{ 
          maxHeight: '70vh', 
          overflow: 'auto',
          border: '1px solid #d9d9d9',
          borderRadius: '8px',
          backgroundColor: '#fff',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          {/* 文档信息栏 */}
          <div style={{
            padding: '16px 20px',
            backgroundColor: '#f8f9fa',
            borderBottom: '1px solid #e9ecef',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div>
                <Text strong style={{ fontSize: '16px' }}>{fileName}</Text>
                <div style={{ marginTop: '4px' }}>
                  {data.warnings && data.warnings.length > 0 && (
                    <Tooltip title={`转换时有 ${data.warnings.length} 个警告，点击查看详情`}>
                      <Tag color="orange" size="small" style={{ cursor: 'pointer' }}>
                        ⚠️ {data.warnings.length} 个警告
                      </Tag>
                    </Tooltip>
                  )}
                  <Tag color="blue" size="small">
                    ✨ 已优化显示
                  </Tag>
                </div>
              </div>
            </div>
            <Space size="small">
              <Tooltip title="下载原文件">
                <Button 
                  size="small"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownload(attachment)}
                >
                  下载
                </Button>
              </Tooltip>
              <Tooltip title="在新窗口打开原文件">
                <Button 
                  size="small"
                  onClick={() => window.open(fileUrl, '_blank')}
                >
                  新窗口
                </Button>
              </Tooltip>
            </Space>
          </div>
          
          {/* HTML内容区域 */}
          <div 
            dangerouslySetInnerHTML={{ __html: data.html }}
            style={{ 
              padding: '0',
              lineHeight: '1.6',
              fontSize: '14px',
              color: '#333'
            }}
          />
          
          {/* 底部提示 */}
          {data.warnings && data.warnings.length > 0 && (
            <div style={{
              padding: '16px 20px',
              backgroundColor: '#fff7e6',
              borderTop: '1px solid #ffd591',
              fontSize: '13px',
              color: '#d46b08'
            }}>
              <details>
                <summary style={{ cursor: 'pointer', fontWeight: 'bold', marginBottom: '8px' }}>
                  📋 转换详情 ({data.warnings.length} 个提示)
                </summary>
                <ul style={{ marginTop: '8px', paddingLeft: '20px', marginBottom: '0' }}>
                  {data.warnings.slice(0, 5).map((warning, index) => (
                    <li key={index} style={{ marginBottom: '4px' }}>
                      {warning.message}
                    </li>
                  ))}
                  {data.warnings.length > 5 && (
                    <li style={{ fontStyle: 'italic' }}>
                      ... 还有 {data.warnings.length - 5} 个提示
                    </li>
                  )}
                </ul>
              </details>
            </div>
          )}
        </div>
      ),
      okText: '关闭',
      onOk: () => modal.destroy()
    });
  };

  // 显示全屏模态框
  const showFullscreenModal = (fileName, html, warnings, attachment, fileUrl) => {
    const fullscreenModal = Modal.info({
      title: (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'space-between',
          gap: '8px',
          paddingRight: '40px'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span>📄</span>
            <span>预览: {fileName}</span>
            <Tag color="blue" size="small">全屏模式</Tag>
          </div>
          <Space size="small">
            <Button 
              size="small"
              type="text"
              icon={<span style={{ fontSize: '16px' }}>⛶</span>}
              title="退出全屏"
              onClick={() => {
                fullscreenModal.destroy();
                // 重新打开普通模态框
                handlePreview(attachment);
              }}
            />
          </Space>
        </div>
      ),
      width: '98%',
      style: { top: 10, maxWidth: 'none' },
      className: 'document-preview-modal fullscreen-modal',
      maskClosable: true,
      content: (
        <div style={{ 
          height: '85vh', 
          overflow: 'auto',
          border: '1px solid #d9d9d9',
          borderRadius: '8px',
          backgroundColor: '#fff',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          {/* 文档信息栏 */}
          <div style={{
            padding: '12px 16px',
            backgroundColor: '#f8f9fa',
            borderBottom: '1px solid #e9ecef',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            position: 'sticky',
            top: 0,
            zIndex: 10
          }}>
            <div>
              <Text strong>{fileName}</Text>
              {warnings && warnings.length > 0 && (
                <Tooltip title={`转换时有 ${warnings.length} 个警告`}>
                  <Tag color="orange" size="small" style={{ marginLeft: 8 }}>
                    {warnings.length} 个警告
                  </Tag>
                </Tooltip>
              )}
            </div>
            <Space size="small">
              <Button 
                size="small"
                icon={<DownloadOutlined />}
                onClick={() => handleDownload(attachment)}
              >
                下载
              </Button>
              <Button 
                size="small"
                onClick={() => window.open(fileUrl, '_blank')}
              >
                新窗口打开
              </Button>
            </Space>
          </div>
          
          {/* HTML内容区域 */}
          <div 
            dangerouslySetInnerHTML={{ __html: html }}
            style={{ 
              padding: '20px',
              lineHeight: '1.6',
              fontSize: '14px',
              color: '#333'
            }}
          />
          
          {/* 底部提示 */}
          {warnings && warnings.length > 0 && (
            <div style={{
              padding: '12px 16px',
              backgroundColor: '#fff7e6',
              borderTop: '1px solid #ffd591',
              fontSize: '12px',
              color: '#d46b08'
            }}>
              <details>
                <summary style={{ cursor: 'pointer', fontWeight: 'bold' }}>
                  转换警告 ({warnings.length})
                </summary>
                <ul style={{ marginTop: '8px', paddingLeft: '20px' }}>
                  {warnings.slice(0, 5).map((warning, index) => (
                    <li key={index} style={{ marginBottom: '4px' }}>
                      {warning.message}
                    </li>
                  ))}
                  {warnings.length > 5 && (
                    <li>... 还有 {warnings.length - 5} 个警告</li>
                  )}
                </ul>
              </details>
            </div>
          )}
        </div>
      ),
      okText: '关闭',
      onOk: () => fullscreenModal.destroy()
    });
  };

  // 显示Office文档模态框
  const showOfficeDocumentModal = (fileName, fileType, fileUrl, attachment) => {
    // 根据文件类型选择预览方式
    if (fileType === 'application/pdf') {
      // PDF文件使用内嵌预览
      const pdfModal = Modal.confirm({
        title: (
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'space-between',
            gap: '8px',
            paddingRight: '40px'
          }}>
            <span>预览: {fileName}</span>
            <Button 
              size="small"
              type="text"
              icon={<span style={{ fontSize: '16px' }}>⛶</span>}
              title="最大化"
              onClick={() => {
                pdfModal.destroy();
                showFullscreenPdfModal(fileName, fileUrl);
              }}
            />
          </div>
        ),
        width: '90%',
        style: { top: 20 },
        maskClosable: true,
        content: (
          <div style={{ height: '70vh' }}>
            <iframe
              src={`${fileUrl}#toolbar=1&navpanes=1&scrollbar=1`}
              style={{ 
                width: '100%', 
                height: '100%', 
                border: 'none',
                borderRadius: '4px'
              }}
              title={fileName}
            />
          </div>
        ),
        okText: '在新窗口打开',
        cancelText: '关闭',
        onOk: () => {
          window.open(fileUrl, '_blank');
        }
      });
    } else if (fileType.includes('officedocument') || fileType.includes('ms-excel') || fileType.includes('msword') || fileType.includes('ms-powerpoint') || fileType.includes('text/plain')) {
      // Office文档和文本文档处理
      const getDocumentIcon = (type) => {
        if (type.includes('word') || type.includes('document')) return '📄';
        if (type.includes('excel') || type.includes('sheet')) return '📊';
        if (type.includes('presentation') || type.includes('powerpoint')) return '📽️';
        if (type.includes('text')) return '📝';
        return '📋';
      };

      const getDocumentTypeName = (type) => {
        if (type.includes('word') || type.includes('document')) return 'Word文档';
        if (type.includes('excel') || type.includes('sheet')) return 'Excel表格';
        if (type.includes('presentation') || type.includes('powerpoint')) return 'PowerPoint演示';
        if (type.includes('text')) return '文本文档';
        return 'Office文档';
      };

      const officeModal = Modal.confirm({
        title: (
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'space-between',
            gap: '8px'
          }}>
            <span>{getDocumentTypeName(fileType)}: {fileName}</span>
          </div>
        ),
        width: '500px',
        maskClosable: true,
        content: (
          <div>
            <div style={{ textAlign: 'center', marginBottom: '16px' }}>
              <div style={{ fontSize: '48px', color: '#1890ff', marginBottom: '8px' }}>
                {getDocumentIcon(fileType)}
              </div>
              <p><strong>{fileName}</strong></p>
              <p style={{ color: '#666', fontSize: '14px' }}>
                文件大小: {attachment.file_size ? Math.round(attachment.file_size / 1024) + ' KB' : '未知'}
              </p>
            </div>
            
            <div style={{ marginBottom: '16px' }}>
              <p>该文档支持在线预览转换。如果转换失败，建议下载原文件获得最佳体验。</p>
            </div>
            
            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
              <Button 
                type="primary" 
                size="large"
                icon={<EyeOutlined />}
                onClick={() => {
                  officeModal.destroy();
                  // 重新尝试转换预览
                  handlePreview(attachment);
                }}
              >
                尝试在线预览
              </Button>
              
              <Button 
                size="large"
                icon={<DownloadOutlined />}
                onClick={() => {
                  handleDownload(attachment);
                  officeModal.destroy();
                }}
              >
                下载原文件
              </Button>
              
              <Button 
                size="large"
                onClick={() => {
                  window.open(fileUrl, '_blank');
                  officeModal.destroy();
                }}
              >
                在新窗口打开
              </Button>
            </div>
            
            <div style={{ marginTop: '16px', padding: '12px', backgroundColor: '#f6f8fa', borderRadius: '6px' }}>
              <p style={{ margin: 0, fontSize: '12px', color: '#666' }}>
                💡 提示：在线预览使用HTML转换技术，下载后可使用Microsoft Office、WPS或其他兼容软件打开查看完整功能
              </p>
            </div>
          </div>
        ),
        okText: '关闭',
        cancelText: null,
        onOk: () => {}
      });
    } else if (fileType.includes('image')) {
      // 图片文件在新窗口打开
      window.open(fileUrl, '_blank');
    } else {
      // 其他文件类型提供选择
      Modal.confirm({
        title: `预览文件: ${fileName}`,
        maskClosable: true,
        content: (
          <div>
            <p>此文件类型可能无法直接在浏览器中预览。</p>
            <p>您可以选择：</p>
            <ul>
              <li>在新窗口中打开（可能会下载）</li>
              <li>直接下载到本地</li>
            </ul>
          </div>
        ),
        okText: '在新窗口打开',
        cancelText: '下载文件',
        onOk: () => {
          window.open(fileUrl, '_blank');
        },
        onCancel: () => {
          handleDownload(attachment);
        }
      });
    }
  };

  // 显示全屏PDF模态框
  const showFullscreenPdfModal = (fileName, fileUrl) => {
    const fullscreenPdfModal = Modal.confirm({
      title: (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'space-between',
          gap: '8px',
          paddingRight: '40px'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span>预览: {fileName}</span>
            <Tag color="blue" size="small">全屏模式</Tag>
          </div>
          <Button 
            size="small"
            type="text"
            icon={<span style={{ fontSize: '16px' }}>⛶</span>}
            title="退出全屏"
            onClick={() => {
              fullscreenPdfModal.destroy();
              showOfficeDocumentModal(fileName, 'application/pdf', fileUrl, { file_size: 0 });
            }}
          />
        </div>
      ),
      width: '98%',
      style: { top: 10, maxWidth: 'none' },
      className: 'document-preview-modal fullscreen-modal',
      maskClosable: true,
      content: (
        <div style={{ height: '85vh' }}>
          <iframe
            src={`${fileUrl}#toolbar=1&navpanes=1&scrollbar=1`}
            style={{ 
              width: '100%', 
              height: '100%', 
              border: 'none',
              borderRadius: '4px'
            }}
            title={fileName}
          />
        </div>
      ),
      okText: '在新窗口打开',
      cancelText: '关闭',
      onOk: () => {
        window.open(fileUrl, '_blank');
      }
    });
  };

  if (!attachments || !Array.isArray(attachments) || attachments.length === 0) {
    return null;
  }

  return (
    <div style={{ marginTop: 24 }}>
      <Typography.Title level={4}>附件 ({attachments.length})</Typography.Title>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
        {attachments.map((attachment) => (
          <Card
            key={attachment.id}
            size="small"
            hoverable
            style={{ borderRadius: 8 }}
            styles={{ body: { padding: 12 } }}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="small">
              {/* 文件预览区域 */}
              <div style={{ textAlign: 'center', minHeight: 80, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {attachment.file_type === 'image' ? (
                  <Image
                    src={getFullUrl(attachment.file_url)}
                    alt={attachment.original_name}
                    style={{ maxWidth: '100%', maxHeight: 80, objectFit: 'cover' }}
                    preview={{
                      mask: <EyeOutlined />
                    }}
                  />
                ) : attachment.file_type === 'video' ? (
                  <video
                    src={getFullUrl(attachment.file_url)}
                    style={{ maxWidth: '100%', maxHeight: 80 }}
                    controls
                    preload="metadata"
                  />
                ) : (
                  <div style={{ fontSize: 32, color: '#1890ff' }}>
                    {getFileIcon(attachment.file_type, attachment.mime_type)}
                  </div>
                )}
              </div>

              {/* 文件信息 */}
              <div>
                <Tooltip title={attachment.original_name}>
                  <Text strong style={{ 
                    display: 'block', 
                    whiteSpace: 'nowrap', 
                    overflow: 'hidden', 
                    textOverflow: 'ellipsis' 
                  }}>
                    {attachment.original_name}
                  </Text>
                </Tooltip>
                
                <Space size="small" wrap style={{ marginTop: 4 }}>
                  <Tag color={getFileTypeColor(attachment.file_type)} size="small">
                    {attachment.file_type}
                  </Tag>
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {formatFileSize(attachment.file_size)}
                  </Text>
                  {attachment.width && attachment.height && (
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {attachment.width}×{attachment.height}
                    </Text>
                  )}
                  {attachment.duration && (
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {Math.floor(attachment.duration / 60)}:{(attachment.duration % 60).toString().padStart(2, '0')}
                    </Text>
                  )}
                </Space>
              </div>

              {/* 操作按钮 */}
              <Space style={{ width: '100%', justifyContent: 'space-between' }}>
                <Button
                  type="text"
                  size="small"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownload(attachment)}
                >
                  下载
                </Button>
                
                {attachment.file_type !== 'image' && (
                  <Button
                    type="text"
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={() => handlePreview(attachment)}
                  >
                    预览
                  </Button>
                )}

                {showActions && onDelete && (
                  <Button
                    type="text"
                    size="small"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => onDelete(attachment.id)}
                  >
                    删除
                  </Button>
                )}
              </Space>
            </Space>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default AttachmentPreview;